package com.ibm.cps.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.storm.guava.base.Throwables;

import com.ibm.cps.message.MessageFields;
import com.ibm.cps.model.ServletUtil;
import com.ibm.interfaces.IPersistency;
import com.ibm.mongo.MongoPersistency;
import com.ibm.util.ErrorCode;
import com.ibm.util.exception.CPSException;

public class Group extends HttpServlet {

	
	private static final long serialVersionUID = 1L;
	private IPersistency persistency;
	private Processors processors;
	private Logger logger;
	
	@Override
	public void init() throws ServletException {
		try {
			logger = Logger.getLogger(Group.class);
			persistency = MongoPersistency.getInstace();
		} catch (CPSException e) {
			logger.error(Throwables.getStackTraceAsString(e));
		}
		processors = Processors.getInstance();
		processors.init();
	}

	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		processors.doDelete(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String retMsg = null;
		try {
			Map<String, String> key2Value = ServletUtil.getParameters(req);
			if (key2Value.get(MessageFields.TENANTID) == null) {
				throw new CPSException(ErrorCode.KEY_NOT_EXIST_CODE, "Please provide the tenantid.");
			}
			Collection<String> groups = persistency.getGroupMetadata(key2Value.get(MessageFields.TENANTID), key2Value.get(MessageFields.GROUPID));
			retMsg= ServletUtil.constructCollectionJson(groups);
		} catch (Throwable e) {
			logger.error(Throwables.getStackTraceAsString(e));
			retMsg = ServletUtil.getException(e);
		} finally {
			PrintWriter writer = resp.getWriter();
			writer.write(retMsg);
			writer.close();
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		processors.doPost(req, resp);
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		processors.doPut(req, resp);
	}

}
